package com.shankungfu.adapter;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.bean.BaseBean;
import com.shankungfu.bean.InterestInBean;
import com.shankungfu.bean.PIHomeCommendBean;
import com.shankungfu.main.ApplyActivity;
import com.shankungfu.main.LogInActivity;
import com.shankungfu.main.PickItemDetailActivity;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.PhoneUtils;
import com.shankungfu.util.TestUtils;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;

public class PickItemAdapter extends BaseAdapter {

	protected static final int FAVORITE = 1;
	protected static final int JOIN = 2;
	protected static final int DATA_SUCCESS = 3;

	private LayoutInflater mInflater;
	private Context context;
	private List<PIHomeCommendBean> homeCommendBeans;
	private DisplayImageOptions options;
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	private ImageLoader imageLoader;
	private int people_interest = 0;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case DATA_SUCCESS:
				InterestInBean interestInBean = (InterestInBean) msg.obj;
				if (interestInBean.getMsg().length() != 0) {
					ToastUtil.showMessageText(context, interestInBean.getMsg());
				}

				break;
			}
		}
	};

	public PickItemAdapter(Context context, DisplayImageOptions options) {
		this.context = context;
		this.options = options;
		imageLoader = ImageLoader.getInstance();
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public void setData(List<PIHomeCommendBean> homeCommendBeans) {
		
		this.homeCommendBeans = homeCommendBeans;
	}

	@Override
	public int getCount() {
		return (homeCommendBeans != null && homeCommendBeans.size() > 0) ? homeCommendBeans
				.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * 这里面不能复用 convertView ，否则会导致图片显示不了。这里最多有九个项目
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
//		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater
					.inflate(R.layout.pickitem_item_layout, null);
			holder.rl = (RelativeLayout) convertView
					.findViewById(R.id.pick_item_content);
			holder.imgView = (ImageView) convertView.findViewById(R.id.imgView);
			holder.category = (Button) convertView.findViewById(R.id.category);
			holder.title = (TextView) convertView.findViewById(R.id.title);
			holder.time = (TextView) convertView.findViewById(R.id.time);
			holder.address = (TextView) convertView.findViewById(R.id.address);
			holder.need_time = (TextView) convertView
					.findViewById(R.id.need_time);
			holder.my_favorite = (TextView) convertView
					.findViewById(R.id.my_favorite);
			holder.want_join = (TextView) convertView
					.findViewById(R.id.want_join);
			holder.textArea = (LinearLayout) convertView
					.findViewById(R.id.pickitem_textArea);
			holder.people_favorite = (LinearLayout) convertView
					.findViewById(R.id.people_favorite);
			holder.people_join = (LinearLayout) convertView
					.findViewById(R.id.people_join);
//			convertView.setTag(holder);
//		} else {
//			holder = (ViewHolder) convertView.getTag();
//		}

		PIHomeCommendBean homeCommendBean = homeCommendBeans.get(position);

		final String projectID = homeCommendBean.getProject_id();

		String startTime = PhoneUtils.TimeStamp2DateForSKF(homeCommendBean
				.getProject_time().getStart_time());
		String endTime = PhoneUtils.TimeStamp2DateForSKF(homeCommendBean
				.getProject_time().getEnd_time());

		holder.category.setText(homeCommendBean.getCategory());
		holder.title.setText(homeCommendBean.getProject_title());
		holder.time.setText("时间：" + startTime + " ~ " + endTime);
		holder.address.setText("地点：" + homeCommendBean.getProject_address());
		holder.need_time.setText("所需志愿时："
				+ homeCommendBean.getProject_services_time() + "小时");

		people_interest = Integer.valueOf(homeCommendBean.getPeople_number());
		holder.my_favorite.setText("我感兴趣\n(" + people_interest + "人)");
		holder.want_join.setText("我要参加\n(" + homeCommendBean.getJoin_number()
				+ "人)");

		imageLoader.displayImage(homeCommendBean.getImg_url(), holder.imgView,
				options, animateFirstListener);
		
		holderViewOnClick(holder, projectID, position);

		return convertView;
	}

	private void holderViewOnClick(final ViewHolder holder,
			final String projectID, final int position) {
		holder.imgView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// ShareSDK.initSDK(context);
				// OnekeyShare oks = new OnekeyShare();
				// oks.setNotification(R.drawable.ic_launcher, "标题");
				// oks.setAddress("地址"); //邮件使用
				// oks.setTitle("标题"); //邮箱，微信
				// oks.setText("内容"); //都用
				// oks.setImagePath("");//图片本地路径 都用
				// oks.setImageUrl(""); //网络图片路径 新浪， 微信中使用
				// oks.setUrl("");//微信使用 视频地址，网页地址
				// // oks.setSilent(silent); //是否直接分享
				// // if (platform) { //分享到指定平台
				// // oks.setPlatform(platform);
				// // }
				// // oks.setCallback(new OnekeyShareCallback());//获取快捷分享的处理结果
				// // oks.setShareContentCustomizeCallback(); //修改不同平台的内容
				//
				// oks.show(context);

				startActivity(projectID);
			}
		});
		holder.textArea.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(projectID);
			}
		});

		holder.my_favorite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				userInteraction(FAVORITE, projectID, position);
			}
		});

		holder.want_join.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				userInteraction(JOIN, projectID, position);
			}
		});

	}

	private void startActivity(String projectID) {
		Intent intent = new Intent(context, PickItemDetailActivity.class);
		intent.putExtra(PickItemDetailActivity.PROJECT_ID, projectID);
		context.startActivity(intent);
	}

	private void userInteraction(int categroy, String project_Id, final int position) {
		if (MainApplication.isUserIsLogin()) { // 将我要感兴趣的Id，发过去

			switch (categroy) {
			case FAVORITE: // 点击了感兴趣
				WebService httpclient = new WebService();
				RequestParams params = new RequestParams();
				params.add("serviceId", "project_interest");
				params.add("app_info", "shankungfu");
				params.add("user_id", MainApplication.userBean.getLoginData()
						.getUser_Id());
				params.add("project_Id", project_Id);
				params.add("user_name", MainApplication.userBean.getLoginData().getUser_name());
				AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						if (!TextUtils.isEmpty(content)) {
							InterestInBean interestInBean = JSON.parseObject(content,
									InterestInBean.class);
							
							homeCommendBeans.get(position).setPeople_number(String.valueOf(interestInBean.getInterest_count()));
							notifyDataSetChanged();
							
							Message msg = new Message();
							msg.what = DATA_SUCCESS;
							msg.obj = interestInBean;
							handler.sendMessage(msg);
						}
					}

					@Override
					public void onFailure(String content) {
					}
				};
				httpclient.request(GlobleConstant.ACTIVITY_INSTEREST_IN,
						params, responseHandler);
				break;
			case JOIN: // 点击了 参加
				Intent intent = new Intent(context, ApplyActivity.class);
				intent.putExtra("project_id", project_Id);
				context.startActivity(intent);
				break;
			}

		} else { // 如果没有登录，就跳到登录页面，登录
			ToastUtil.showMessageText(context, "请先登录");
			Intent intent = new Intent(context, LogInActivity.class);
			context.startActivity(intent);
		}
	}

	private class ViewHolder {
		private RelativeLayout rl;
		private LinearLayout textArea;
		private ImageView imgView;
		private Button category;
		private TextView title;
		private TextView time;
		private TextView address;
		private TextView need_time;
		private TextView my_favorite;
		private TextView want_join;
		private LinearLayout people_favorite;
		private LinearLayout people_join;
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

}
